package com.cn.fw4j.util.httpclient;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;


import com.cn.fw4j.util.StreamHelper;


public class HttpClientHelper {
	public static String post(String url,Map<String,String> param) throws ClientProtocolException, IOException{
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		for(String key : param.keySet()){
			params.add(new BasicNameValuePair(key, param.get(key)));
		}
		HttpPost post = new HttpPost();
		post.addHeader("Accept-Charset", "utf-8");
		post.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpResponse resp = httpClient.execute(post);
		HttpEntity entity = resp.getEntity();
		if(entity != null){
			return StreamHelper.getContent(entity.getContent());
		}
		return null;
	}
	
	public static String get(String url,Map<String,String> param) throws ClientProtocolException, IOException{
			StringBuilder url2 = new StringBuilder(url);
			if(param != null){
				url2.append("?");
				for(String key : param.keySet()){
					url2.append(key);
					url2.append("=");
					url2.append(param.get(key));
					url2.append("&");
				}
				url2.replace(url2.lastIndexOf("&"), url2.length(), "");
			}
			HttpGet get = new HttpGet(url2.toString());
			get.addHeader("Accept-Charset", "utf-8");
			CloseableHttpClient httpClient = HttpClients.createDefault();
			HttpResponse resp = httpClient.execute(get);
			HttpEntity entity = resp.getEntity();
			if(entity != null){
				return StreamHelper.getContent(entity.getContent());
			}
			return null;
	}
}
